;;; init-evil.el --- Evil configuration -*- lexical-binding: t -*-
;;; Commentary:
;;; Code:

(global-set-key (kbd "s-y") (lambda ()
                              (interactive)
                              (require 'evil)
                              (evil-local-mode)
                              (global-set-key (kbd "s-y") #'evil-local-mode)))

(setq evil-want-Y-yank-to-eol t)
(setq evil-undo-system 'undo-redo)
(setq evil-toggle-key "")
(setq evil-mode-line-format '(after . mode-line-remote))
(setq evil-disable-insert-state-bindings t)

(with-eval-after-load 'evil
  ;; Make underscore and dash as part of word character
  ;; see https://www.github.com/emacs-evil/evil/blob/master/doc/source/faq.rst#underscore-is-not-a-word-character
  (defalias 'forward-evil-word 'forward-evil-symbol)

  ;; {{ Replace evil-insert-state with evil-emacs-state.
  ;; (defalias 'evil-insert-state 'evil-emacs-state)
  ;; (define-key evil-emacs-state-map (kbd "<escape>") #'evil-normal-state)
  ;; (setq evil-emacs-state-cursor '(bar . 2))

  ;; Visual editing will enter emacs-state, it not gonna work as expect.
  ;; Use `string-insert-rectangle' to get input words.
  ;; (define-key evil-visual-state-map "I" #'string-insert-rectangle)
  ;; }}

  (defun ctrlwei/insert-empty-line-below (lines)
    "Insert numbers of LINES empty line below the current line."
    (interactive "P")
    (let ((lines (if lines lines 1)))
      (save-excursion
        (end-of-line)
        (open-line lines))))

  (defun ctrlwei/insert-empty-line-above (lines)
    "Insert an numbers of LINES empty line above the current line."
    (interactive "P")
    (let ((lines (if lines lines 1)))
      (save-excursion
        (end-of-line 0)
        (open-line lines))))

  ;; {{ Key bindings
  (evil-set-leader '(normal visual) (kbd "SPC"))
  (evil-global-set-key 'normal "U" #'evil-redo)
  (evil-global-set-key 'normal "H" #'mwim-beginning-of-code-or-line-or-comment)
  (evil-global-set-key 'normal "L" #'mwim-end-of-code-or-line)
  (evil-define-key 'normal 'global (kbd "<leader> SPC") #'execute-extended-command)
  (evil-define-key 'normal 'global (kbd "<leader> c SPC") #'comment-line)
  (evil-define-key 'visual 'global (kbd "<leader> c SPC") #'comment-or-uncomment-region)
  (evil-define-key 'visual 'global (kbd "TAB") #'indent-region)
  (evil-define-key 'normal 'global (kbd "<leader> o") #'ctrlwei/insert-empty-line-below)
  (evil-define-key 'normal 'global (kbd "<leader> O") #'ctrlwei/insert-empty-line-above)
  (evil-define-key 'normal 'global (kbd "<leader>ff") #'find-file)
  (evil-define-key 'normal 'global (kbd "<leader>fg") #'projectile-find-file)
  (evil-define-key 'normal 'global (kbd "<leader>bb") #'switch-to-buffer)
  (evil-define-key 'normal 'global (kbd "<leader>bd") #'kill-current-buffer)
  (evil-define-key 'normal 'global (kbd "<leader>gs") #'magit-status)
  ;; }}
  )
(provide 'init-evil)
;;; init-evil.el ends here
